package com.fenghuajueli.idiomppp.ui.idiompin;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;

import com.blankj.utilcode.util.LogUtils;
import com.fenghuajueli.idiomppp.database.IdiomDaoUtils;
import com.fenghuajueli.idiomppp.db.Caimi;
import com.fenghuajueli.idiomppp.db.CaimiDao;
import com.fenghuajueli.idiomppp.db.DatabaseManager;
import com.fenghuajueli.idiomppp.entity.GuessAnswerEntity;
import com.fenghuajueli.idiomppp.entity.GuessIdiomEntity;
import com.fenghuajueli.idiomppp.entity.IdiomPinDbEntity;
import com.fenghuajueli.idiomppp.entity.IdiomPinEntity;
import com.fenghuajueli.idiomppp.entity.IdiomPinParentEntity;
import com.fenghuajueli.idiomppp.entity.IdiomXiaoDbEntity;
import com.fenghuajueli.idiomppp.utils.CaiChengYuData;
import com.fenghuajueli.idiomppp.utils.ChengYuData;
import com.fenghuajueli.idiomppp.utils.RuntimeDataUtils;
import com.fenghuajueli.libbasecoreui.mvp.BasePresenter;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class IdiomSelectPassPresenter extends BasePresenter<IdiomSelectPassView> {
    CompositeDisposable compositeDisposable = new CompositeDisposable();
    private int currentPage = 0;//当前第几页
    private int pageSize = 25;//每一页的大小
    private int allCount = 0;//数据总数
    private int allPages = 0;//总的页数
    private List<IdiomPinParentEntity> idiomPinParentEntityList;
    private List<IdiomPinParentEntity> idiomJieLongParentEntityList;
    private List<IdiomXiaoDbEntity> idiomXiaoDbEntityList;
    private List<GuessIdiomEntity> guessIdiomEntityList;
    private CaimiDao caimiDao;
    private Context context;

    public IdiomSelectPassPresenter(Context mContext) {
        super(mContext);
        context = mContext;
        idiomPinParentEntityList = new ArrayList<>();
        idiomJieLongParentEntityList = new ArrayList<>();
        idiomXiaoDbEntityList = new ArrayList<>();
        guessIdiomEntityList = new ArrayList<>();
    }

    public void initData() {
        if (RuntimeDataUtils.idiomPinParentEntityList == null) {
//            getView().showLoading("初始化中...");
            Observable.create(new ObservableOnSubscribe<List<IdiomPinParentEntity>>() {
                        @Override
                        public void subscribe(ObservableEmitter<List<IdiomPinParentEntity>> emitter) throws Exception {
                            List<IdiomPinParentEntity> idiomPinParentEntityList = new ArrayList<>();
                            List<IdiomPinDbEntity> idiomPinDbEntityList = IdiomDaoUtils.getIdiomPinManager().listAll();
                            for (int i = 0; i < idiomPinDbEntityList.size(); i++) {
                                String[] data = idiomPinDbEntityList.get(i).getContent().split("\n");
                                List<IdiomPinEntity> idiomPinEntityList = new ArrayList<>();
                                for (int j = 0; j < data.length; j++) {
                                    String[] current = data[j].split(",");
                                    IdiomPinEntity idiomPinEntity = new IdiomPinEntity(Integer.parseInt(current[0]),
                                            Integer.parseInt(current[1]), Integer.parseInt(current[3]), current[2]);
                                    idiomPinEntity.setIndex(i);
                                    idiomPinEntityList.add(idiomPinEntity);
                                }
                                IdiomPinParentEntity idiomPinParentEntity = new IdiomPinParentEntity(i, idiomPinEntityList);
                                idiomPinParentEntityList.add(idiomPinParentEntity);
                            }
                            idiomPinParentEntityList = idiomPinParentEntityList.subList(0, 1800);
                            allCount = idiomPinParentEntityList.size();
                            RuntimeDataUtils.idiomPinParentEntityList = idiomPinParentEntityList;
                            emitter.onNext(idiomPinParentEntityList);
                        }
                    }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<IdiomPinParentEntity>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            compositeDisposable.add(d);
                        }

                        @Override
                        public void onNext(List<IdiomPinParentEntity> idiomPinParentEntities) {
                            getView().hideLoading();
                            getNextPageData();
                        }

                        @Override
                        public void onError(Throwable e) {
                            LogUtils.e(e);
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            allCount = RuntimeDataUtils.idiomPinParentEntityList.size();
            getNextPageData();
        }
    }

    public void getNextPageData() {
        if (allCount % pageSize == 0) {
            allPages = allCount / pageSize;
        } else {
            allPages = allCount / pageSize + 1;
        }
        currentPage++;
        if (currentPage == allPages) {
            getView().changeBtnNextView(View.GONE);
        }
        if (currentPage > 1) {
            getView().changeBtnUpView(View.VISIBLE);
        }
        int endIndex = 0;
        if (currentPage * pageSize > allCount) {
            endIndex = allCount;
        } else {
            endIndex = currentPage * pageSize;
        }
        idiomPinParentEntityList = RuntimeDataUtils.idiomPinParentEntityList.subList((currentPage - 1) * pageSize, endIndex);
        getView().loadSuccess(idiomPinParentEntityList);

    }

    public void getUpPageData() {
        if (currentPage > 1) {
            currentPage--;
            if (currentPage == 1) {
                getView().changeBtnUpView(View.GONE);
            }
            getView().changeBtnNextView(View.VISIBLE);
            int endIndex = 0;
            if (currentPage * pageSize > allCount) {
                endIndex = allCount;
            } else {
                endIndex = currentPage * pageSize;
            }
            idiomPinParentEntityList = RuntimeDataUtils.idiomPinParentEntityList.subList((currentPage - 1) * pageSize, endIndex);
        } else {
            currentPage = 1;
            idiomPinParentEntityList = RuntimeDataUtils.idiomPinParentEntityList.subList((currentPage - 1) * pageSize, currentPage * pageSize);
            getView().changeBtnUpView(View.GONE);
        }
        getView().loadSuccess(idiomPinParentEntityList);
    }

    public void initJieLongData() {
        if (RuntimeDataUtils.idiomJieLongParentEntityList == null) {
//            getView().showLoading("初始化中...");
            Observable.create((ObservableOnSubscribe<List<IdiomPinParentEntity>>) emitter -> {
                        List<IdiomPinParentEntity> idiomPinParentEntityList = new ArrayList<>();
                        List<IdiomPinDbEntity> idiomPinDbEntityList = IdiomDaoUtils.getIdiomPinManager().listAll();
                        for (int i = 0; i < idiomPinDbEntityList.size(); i++) {
                            String[] data = idiomPinDbEntityList.get(i).getContent().split("\n");
                            List<IdiomPinEntity> idiomPinEntityList = new ArrayList<>();
                            for (int j = 0; j < data.length; j++) {
                                String[] current = data[j].split(",");
                                IdiomPinEntity idiomPinEntity = new IdiomPinEntity(Integer.parseInt(current[0]),
                                        Integer.parseInt(current[1]), Integer.parseInt(current[3]), current[2]);
                                idiomPinEntity.setIndex(i);
                                idiomPinEntityList.add(idiomPinEntity);
                            }
                            IdiomPinParentEntity idiomPinParentEntity = new IdiomPinParentEntity(i, idiomPinEntityList);
                            idiomPinParentEntityList.add(idiomPinParentEntity);
                        }
                        idiomPinParentEntityList = idiomPinParentEntityList.subList(1800, idiomPinParentEntityList.size());
                        allCount = idiomPinParentEntityList.size();
                        RuntimeDataUtils.idiomJieLongParentEntityList = idiomPinParentEntityList;
                        emitter.onNext(idiomPinParentEntityList);
                    }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<IdiomPinParentEntity>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            compositeDisposable.add(d);
                        }

                        @Override
                        public void onNext(List<IdiomPinParentEntity> idiomPinParentEntities) {
//                            getView().hideLoading();
                            getJieLongNextPageData();
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            allCount = RuntimeDataUtils.idiomJieLongParentEntityList.size();
            getJieLongNextPageData();
        }
    }

    public void getJieLongNextPageData() {
        if (allCount % pageSize == 0) {
            allPages = allCount / pageSize;
        } else {
            allPages = allCount / pageSize + 1;
        }
        currentPage++;
        if (currentPage == allPages) {
            getView().changeBtnNextView(View.GONE);
        }
        if (currentPage > 1) {
            getView().changeBtnUpView(View.VISIBLE);
        }
        int endIndex = 0;
        if (currentPage * pageSize > allCount) {
            endIndex = allCount;
        } else {
            endIndex = currentPage * pageSize;
        }
        idiomJieLongParentEntityList = RuntimeDataUtils.idiomJieLongParentEntityList.subList((currentPage - 1) * pageSize, endIndex);
        getView().loadSuccess(idiomJieLongParentEntityList);

    }

    public void getJieLongUpPageData() {
        if (currentPage > 1) {
            currentPage--;
            if (currentPage == 1) {
                getView().changeBtnUpView(View.GONE);
            }
            getView().changeBtnNextView(View.VISIBLE);
            int endIndex = 0;
            if (currentPage * pageSize > allCount) {
                endIndex = allCount;
            } else {
                endIndex = currentPage * pageSize;
            }
            idiomJieLongParentEntityList = RuntimeDataUtils.idiomJieLongParentEntityList.subList((currentPage - 1) * pageSize, endIndex);
        } else {
            currentPage = 1;
            idiomJieLongParentEntityList = RuntimeDataUtils.idiomJieLongParentEntityList.subList((currentPage - 1) * pageSize, currentPage * pageSize);
            getView().changeBtnUpView(View.GONE);
        }
        getView().loadSuccess(idiomJieLongParentEntityList);
    }


    public void initXiaoXiaoData() {
        if (RuntimeDataUtils.idiomXiaoDbEntityList == null) {
//            getView().showLoading("初始化中...");
            Observable.create((ObservableOnSubscribe<List<IdiomXiaoDbEntity>>) emitter -> {
                        List<IdiomXiaoDbEntity> idiomPinDbEntityList = IdiomDaoUtils.getIdiomXiaoXiaoManager().listAll();
                        allCount = idiomPinDbEntityList.size();
                        LogUtils.d("成语消消数据长度：" + allCount);
                        RuntimeDataUtils.idiomXiaoDbEntityList = idiomPinDbEntityList;
                        emitter.onNext(idiomPinDbEntityList);
                    }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<IdiomXiaoDbEntity>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            compositeDisposable.add(d);
                        }

                        @Override
                        public void onNext(List<IdiomXiaoDbEntity> idiomPinParentEntities) {
//                            getView().hideLoading();
                            getXiaoNextPageData();
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            allCount = RuntimeDataUtils.idiomXiaoDbEntityList.size();
            getXiaoNextPageData();
        }
    }


    public void getXiaoNextPageData() {
        if (allCount % pageSize == 0) {
            allPages = allCount / pageSize;
        } else {
            allPages = allCount / pageSize + 1;
        }
        currentPage++;
        if (currentPage == allPages) {
            getView().changeBtnNextView(View.GONE);
        }
        if (currentPage > 1) {
            getView().changeBtnUpView(View.VISIBLE);
        }
        int endIndex = 0;
        if (currentPage * pageSize > allCount) {
            endIndex = allCount;
        } else {
            endIndex = currentPage * pageSize;
        }
        idiomXiaoDbEntityList = RuntimeDataUtils.idiomXiaoDbEntityList.subList((currentPage - 1) * pageSize, endIndex);
        getView().loadXiaoDataSuccess(idiomXiaoDbEntityList);

    }


    public void getXiaoUpPageData() {
        if (currentPage > 1) {
            currentPage--;
            if (currentPage == 1) {
                getView().changeBtnUpView(View.GONE);
            }
            getView().changeBtnNextView(View.VISIBLE);
            int endIndex = 0;
            if (currentPage * pageSize > allCount) {
                endIndex = allCount;
            } else {
                endIndex = currentPage * pageSize;
            }
            idiomXiaoDbEntityList = RuntimeDataUtils.idiomXiaoDbEntityList.subList((currentPage - 1) * pageSize, endIndex);
        } else {
            currentPage = 1;
            idiomXiaoDbEntityList = RuntimeDataUtils.idiomXiaoDbEntityList.subList((currentPage - 1) * pageSize, currentPage * pageSize);
            getView().changeBtnUpView(View.GONE);
        }
        getView().loadXiaoDataSuccess(idiomXiaoDbEntityList);
    }

    /**
     * 初始化字谜数据
     */
    public void initWordRiddleData() {
        if (guessIdiomEntityList.size() == 0) {
            caimiDao = DatabaseManager.getInstance(context).getCaimiDatabase().caimiDao();
            char[] randomWord = CaiChengYuData.jianTiChar.toCharArray();
            Observable.just(1)
                    .map(integer -> caimiDao.loadDataByTitle("字谜"))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<Caimi>>() {
                        @Override
                        public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@io.reactivex.annotations.NonNull List<Caimi> caimis) {
                            if (caimis.size() > 0) {
                                List<GuessIdiomEntity> guessIdiomEntities = new ArrayList<>();
                                for (int i = 0; i < caimis.size(); i++) {
                                    Caimi caimi = caimis.get(i);
                                    if (TextUtils.isEmpty(caimi.getQuestion()) || TextUtils.isEmpty(caimi.getAnswer()) || TextUtils.isEmpty(caimi.getInfo())) {
                                        continue;
                                    }
                                    String question = caimi.getQuestion();
                                    String answer = caimi.getAnswer();
                                    GuessIdiomEntity guessIdiomEntity = new GuessIdiomEntity(i, "", question.substring(question.indexOf("：") + 1, question.indexOf("（")),
                                            answer.substring(answer.indexOf("：") + 1), caimi.getInfo());
                                    //生成随机问字答案
                                    List<GuessAnswerEntity> guessAnswerEntities = new ArrayList<>();
                                    for (int j = 0; j < 17; j++) {
                                        int index = (i / 5 + randomWord.length) / (j + 2);
                                        guessAnswerEntities.add(new GuessAnswerEntity(String.valueOf(randomWord[index])));
                                    }
                                    String wordAnswer = guessIdiomEntity.getWordAnswer();
                                    guessAnswerEntities.add(new GuessAnswerEntity(wordAnswer.substring(wordAnswer.indexOf("：") + 1)));
                                    Collections.shuffle(guessAnswerEntities);
                                    guessIdiomEntity.setAnswerWord(guessAnswerEntities);
                                    guessIdiomEntities.add(guessIdiomEntity);
                                }
                                allCount = guessIdiomEntities.size();
                                guessIdiomEntityList = guessIdiomEntities;
                                getGuessIdiomNextPageData();
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e("dsqeceData", "onError:" + e.getMessage());
                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        } else {
            allCount = guessIdiomEntityList.size();
            getGuessIdiomNextPageData();
        }
    }

    /**
     * 初始化谜语数据
     */
    public void initRiddleData() {
        if (guessIdiomEntityList.size() == 0) {
            caimiDao = DatabaseManager.getInstance(context).getCaimiDatabase().caimiDao();
            char[] randomWord = CaiChengYuData.jianTiChar.toCharArray();
            Observable.just(1)
                    .map(integer -> caimiDao.loadAllData())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<Caimi>>() {
                        @Override
                        public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@io.reactivex.annotations.NonNull List<Caimi> caimis) {
                            if (caimis.size() > 0) {
                                List<GuessIdiomEntity> guessIdiomEntities = new ArrayList<>();
                                for (int i = 0; i < caimis.size(); i++) {
                                    Caimi caimi = caimis.get(i);
                                    if (TextUtils.isEmpty(caimi.getQuestion()) || TextUtils.isEmpty(caimi.getAnswer()) || TextUtils.isEmpty(caimi.getInfo())) {
                                        continue;
                                    }
                                    String question = caimi.getQuestion();
                                    String answer = caimi.getAnswer();
                                    String riddleAnswer = answer.substring(answer.indexOf("：") + 1);
                                    if (riddleAnswer.length() != 3) {
                                        continue;
                                    }
                                    Log.e("dsqeceData", "onNext---->:" + riddleAnswer);
                                    String riddleQuestion = "";
                                    if (question.contains("（")) {
                                        riddleQuestion = question.substring(question.indexOf("：") + 1, question.indexOf("（"));
                                    } else {
                                        riddleQuestion = question.substring(question.indexOf("：") + 1);
                                    }
                                    GuessIdiomEntity guessIdiomEntity = new GuessIdiomEntity(i, "", riddleQuestion,
                                            riddleAnswer, caimi.getInfo());
                                    //生成随机问字答案
                                    List<GuessAnswerEntity> guessAnswerEntities = new ArrayList<>();
                                    for (int j = 0; j < 15; j++) {
                                        int index = (i / 20 + randomWord.length) / (j + 2);
                                        guessAnswerEntities.add(new GuessAnswerEntity(String.valueOf(randomWord[index])));
                                    }
                                    String wordAnswer = guessIdiomEntity.getWordAnswer();
                                    Log.e("dsqeceData", "onNext--wordAnswer-->:" + wordAnswer);
                                    for (int k = 0; k < wordAnswer.length(); k++) {
                                        char[] wordAnswerArray = wordAnswer.toCharArray();
                                        guessAnswerEntities.add(new GuessAnswerEntity(String.valueOf(wordAnswerArray[k])));
                                    }
                                    Log.e("dsqeceData", "answer--------->" + wordAnswer + "=======" + wordAnswer.substring(wordAnswer.indexOf("：") + 1));
                                    Collections.shuffle(guessAnswerEntities);
                                    guessIdiomEntity.setAnswerWord(guessAnswerEntities);
                                    guessIdiomEntities.add(guessIdiomEntity);
                                }
                                allCount = guessIdiomEntities.size();
                                Log.e("dsqeceData", "size allCount:" + allCount + "-------->" + caimis.size());
                                guessIdiomEntityList = guessIdiomEntities;
                                getGuessIdiomNextPageData();
                                Log.e("dsqeceData", "idiomselectpasspresenter:" + guessIdiomEntities.get(0).toString());
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e("dsqeceData", "onError:" + e.getMessage());
                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        } else {
            allCount = guessIdiomEntityList.size();
            getGuessIdiomNextPageData();
        }
    }

    /**
     * 初始化看图猜成语数据
     */
    public void initGuessIdiomData() {
        if (guessIdiomEntityList.size() == 0) {
//            getView().showLoading("初始化中...");
            char[] randomWord = CaiChengYuData.jianTiChar.toCharArray();
            Observable.create((ObservableOnSubscribe<List<GuessIdiomEntity>>) emitter -> {
                        List<GuessIdiomEntity> guessIdiomEntities = new ArrayList<>();
                        for (int i = 0; i < ChengYuData.cheng_yu_array.length - 200; i++) {
                            GuessIdiomEntity guessIdiomEntity = new GuessIdiomEntity(i, (i + 201) + ".png", ChengYuData.cheng_yu_array[i + 200], "", "");
                            //生成随机问字答案
                            List<GuessAnswerEntity> guessAnswerEntities = new ArrayList<>();
                            for (int j = 0; j < 14; j++) {
                                int index = (i * 5 + randomWord.length) / (j + 2);
                                guessAnswerEntities.add(new GuessAnswerEntity(String.valueOf(randomWord[index])));
                            }
                            for (int j = 0; j < guessIdiomEntity.getIdiom().length(); j++) {
                                char[] data = guessIdiomEntity.getIdiom().toCharArray();
                                guessAnswerEntities.add(new GuessAnswerEntity(String.valueOf(data[j])));
                            }
                            Collections.shuffle(guessAnswerEntities);
                            guessIdiomEntity.setAnswerWord(guessAnswerEntities);
                            guessIdiomEntities.add(guessIdiomEntity);
                        }
                        allCount = guessIdiomEntities.size();
                        LogUtils.d("看图猜成语数据长度：" + allCount);
                        guessIdiomEntityList = guessIdiomEntities;
                        emitter.onNext(guessIdiomEntities);
                    }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<GuessIdiomEntity>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            compositeDisposable.add(d);
                        }

                        @Override
                        public void onNext(List<GuessIdiomEntity> idiomPinParentEntities) {
//                            getView().hideLoading();
                            getGuessIdiomNextPageData();
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            allCount = guessIdiomEntityList.size();
            getGuessIdiomNextPageData();
        }
    }

    public static char getRandomChar() {
        return (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1)));
    }

    public void getGuessIdiomNextPageData() {
        if (allCount % pageSize == 0) {
            allPages = allCount / pageSize;
        } else {
            allPages = allCount / pageSize + 1;
        }
        currentPage++;
        if (currentPage == allPages) {
            getView().changeBtnNextView(View.GONE);
        }
        if (currentPage > 1) {
            getView().changeBtnUpView(View.VISIBLE);
        }
        int endIndex = 0;
        if (currentPage * pageSize > allCount) {
            endIndex = allCount;
        } else {
            endIndex = currentPage * pageSize;
        }
        getView().loadGuessDataSuccess(guessIdiomEntityList.subList((currentPage - 1) * pageSize, endIndex));
    }

    public void getGuessIdiomUpPageData() {
        if (currentPage > 1) {
            currentPage--;
            if (currentPage == 1) {
                getView().changeBtnUpView(View.GONE);
            }
            getView().changeBtnNextView(View.VISIBLE);
            int endIndex = 0;
            if (currentPage * pageSize > allCount) {
                endIndex = allCount;
            } else {
                endIndex = currentPage * pageSize;
            }
            getView().loadGuessDataSuccess(guessIdiomEntityList.subList((currentPage - 1) * pageSize, endIndex));
        } else {
            currentPage = 1;
            getView().changeBtnUpView(View.GONE);
            getView().loadGuessDataSuccess(guessIdiomEntityList.subList((currentPage - 1) * pageSize, currentPage * pageSize));
        }
    }


    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        super.onDestroy(owner);
        compositeDisposable.dispose();
        compositeDisposable.clear();
    }
}
